package ch13.collecting;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectingResults {
    public static void main(String[] args) throws IOException {
        // 1开始，每次返回值作为下一次的参数
        var iter = Stream.iterate(1, i -> i + 1).limit(10).iterator();
        while (iter.hasNext()) {
            System.out.println(iter.next());
        }

        // Object[]
        var numbers = Stream.iterate(0, i -> i + 1)
                        .limit(10).toArray();
        System.out.println("Object array:" + numbers);

        try {
            var number = numbers[0];
            System.out.println("number: " + number);
            System.out.println("The following statement throws an exception:");
            var numbers2 = (Integer[])numbers;   // Object[] numbers不可以转
        }
        catch (ClassCastException e) {
            System.out.println(e);
        }

        // Integer[]
        var numbers3 = Stream.iterate(0, i -> i + 1)
                        .limit(10).toArray(Integer[]::new);
        System.out.println("Integer array:" + numbers3);

        // 无序
        var noVowelSet = noVowels().collect(Collectors.toSet());
        show("noVowelSet", noVowelSet);

        // 有排序
        var noVowelTreeSet = noVowels().collect(
            Collectors.toCollection(TreeSet::new));
        show("noVowelTreeSet", noVowelTreeSet);

        var result = noVowels().limit(10).collect(Collectors.joining());
        System.out.println("Joining: " + result);

        result = noVowels().limit(10).collect(Collectors.joining(", "));
        System.out.println("Joining with commas: " + result);

        var summary = noVowels().limit(10)
                .collect(Collectors.summarizingInt(String::length));
        var averageWordLength = summary.getAverage();
        var maxWordLength = summary.getMax();
        System.out.println("Average word length: " + averageWordLength);
        System.out.println("Max word length: " + maxWordLength);

        System.out.println("forEach:");
        noVowels().limit(10).forEach(System.out::println);
    }

    // 没有元音
    public static Stream<String> noVowels() throws IOException {
        var contents = Files.readString(
            Path.of("ch09/set/alice30.txt")
        );

        var wordList = List.of(contents.split("\\PL+"));
        var words = wordList.stream();
        return words.map(s -> s.replaceAll("[aeiouAEIO]", ""));
    }

    public static <T> void show(String label, Set<T> set) {
        System.out.println(label + ": " + set.getClass().getName());
        System.out.println("["
            + set.stream().limit(10).map(Object::toString)
                .collect(Collectors.joining(", "))
            + "]"
        );
    }
}
